from fastapi import APIRouter, UploadFile, File, HTTPException, Depends, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from typing import Optional, Any, Dict
import numpy as np
import soundfile as sf
from io import BytesIO
import os
from utils.file_handler import save_temp_file, remove_temp_file
from utils.logger import setup_logger
from config import MODEL_CONFIG
from models.dependencies import get_dependencies
import whisper

# 假设ModelHandler和ModelConfig定义在你的代码中
from data_handler.data_model_process import ModelHandler
from config import ModelConfig,MODEL_CONFIG  # 替换为实际模块路径

# ChatTTS 路由
router_chattts = APIRouter(prefix="/chattts", tags=["ChatTTS"])
logger = setup_logger()

class ChatTTSConfig(BaseModel):
    text: str
    speaker: str = MODEL_CONFIG.chattts_speaker
    speed: float = 1.0
    temperature: float = 0.7
    stream: bool = False  # 添加 stream 字段以支持流式控制

@router_chattts.post("/generate")
async def generate_speech(
    config: ChatTTSConfig,
    dependencies: Dict = Depends(get_dependencies)
):
    """
    生成 ChatTTS 语音（非流式）。
    - 输入: ChatTTSConfig（包含 text, speaker, speed, temperature）
    - 输出: WAV 音频文件
    """
    try:
        handler = ModelHandler()
        # 转换 ChatTTSConfig 为 ModelConfig
        model_config = ModelConfig(
            model="chattts",  # 假设固定模型名称
            model_name="chattts",  # 假设固定模型名称
            temperature=config.temperature,
            max_tokens=512,  # 默认值，可根据需要调整
            stream=config.stream,
            text=config.text,  # 传递文本
            speaker=config.speaker,  # 扩展字段
            speed=config.speed,  # 扩展字段
            chattts_model_dir=MODEL_CONFIG.chattts_model_dir
        )
        # 调用 ModelHandler
        result = await handler.call_model(
            model="chattts",
            model_type="chattts",
            data=config.text,  # 传递文本作为 prompt
            streaming=False,  # 强制非流式
            config=model_config,
            dependencies=dependencies
        )
        return result  # 假设返回 StreamingResponse（音频）
    except Exception as e:
        logger.error(f"ChatTTS 处理失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"语音生成失败: {str(e)}")